package com.yang.webapi.auth;

import com.yang.security.model.LoginUser;
import com.yang.security.model.person.WeChatPerson;
import com.yang.service.api.UserService;
import com.yang.service.model.vo.UserVO;
import com.zhy.base.tools.beans.BeanMapper;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.Objects;



/**
 * Created by baipan
 * Date: 2019-12-18
 * SpringSecurity获取用户实现类
 */
@Component
@Slf4j
@Primary
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private UserService userService;
    @Autowired
    private BeanMapper beanMapper;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVO userVO = userService.findByUserName(username);
        if (Objects.isNull(userVO)) {
            throw new AuthenticationCredentialsNotFoundException("用户名不存在");
        }

        WeChatPerson weChatPerson = beanMapper.map(userVO, WeChatPerson.class);
        LoginUser user = LoginUser.build(weChatPerson);

        //获取用户的权限 (暂时不加入权限，登录即可访问接口资源)
        user.setPermissions(Lists.emptyList());
        return user;
    }


}
